package bro2Advanced.threads;


import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;


public class SimpleWebServer {
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = 2 * CPU_COUNT;
    private static final int MAX_POOL_SIZE = 2 * CPU_COUNT + 1;

    private static final ThreadPoolExecutor exec = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000));

    static {
        System.out.println(CPU_COUNT);
    }

    /**
     * Web服务器通常需要处理I/O操作
     */
    @Test
    public void testSimpleWebServer() {
        while (true) {
            Runnable request = () -> System.out.println("request handled by " + Thread.currentThread().getName());

            exec.execute(request);
            System.out.println(exec.getTaskCount());
        }
    }

    /**
     * 并行计算任务主要用于计算
     */
    @Test
    public void testParallelCalculation() {
        Callable<Double> task = () -> Math.random() * 100;

        List<Future<Double>> results = new ArrayList<>();

        for (int i = 0; i < 10; i ++) {
            results.add(exec.submit(task));
        }

        for (Future<Double> result: results) {
            try {
                System.out.println(result.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        exec.shutdown();
    }
    /**
     * 异步任务处理
     */
    @Test
    public void testAsynchronousTaskProcessor() {
        exec.execute(() -> {
            System.out.println("Async task started");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Async task completed");
        });

        System.out.println("Main thread continues to execute other operations.");
        exec.shutdown();
    }
}
